import { defineStore } from "pinia";
import { getUserInfo } from "@/http/api";
import { ElLoading, ElMessage } from "element-plus";
import router from "@/router/index";

/**
 * 用户信息Store
 */
export const useUserStore = defineStore("user", {
  // 状态（相当于Vuex的state）
  state: () => ({
    // 用户基本信息
    loginData: {},
    // 登录状态
    isLoggedIn: false,
  }),

  // 计算属性（相当于Vuex的getters）
  getters: {
    // 获取用户名
    firstName: (state) => {
      return state.loginData.user_name
        ? state.loginData.user_name.substring(0, 1).toUpperCase()
        : "U";
    },
    userInfo: (state) => {
      return {
        user_name: state.loginData.user_name || "Admin",
        role_name: state.loginData.role_name || "管理员",
      };
    },
    perms: (state) => {
      return state.loginData.perms || "";
    },
  },

  // 方法（相当于Vuex的mutations和actions合并）
  actions: {
    //获取用户信息
    async getUserInfo() {
      const loading = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      try {
        const resData = await getUserInfo();
        if (resData) {
          this.loginData = { ...resData };
          this.isLoggedIn = true;
        }
      } catch (error) {
      } finally {
        setTimeout(() => {
          loading.close();
        }, 100);
      }
    },
    //设置登录时返回的信息
    setLogin(resData) {
      this.loginData = { ...resData };
      this.isLoggedIn = true;
    },
    // 用户登出
    logout() {
      this.loginData = {};
      this.isLoggedIn = false;
      this.perms = [];
      localStorage.removeItem("token");
      router.push("/login");
    },
  },
});
